var $api = require('../../utils/api.js'); //引入api.js页面  
var area_standard = require('../../utils/areaStandard');
Page({
    data: {
        //判断小程序的API，回调，参数，组件等是否在当前版本可用。
        searchTag: "", //搜索tag名称

        carSource: [], //车源列表
        nowpage: 1, //列表页码
        isHideLoadMore: true, //下拉加载
        noMore: true, //没有更多数据提示
        brand: '',
        region: '',
        showCityPopup: false,
        city:'',
    },

    onLoad: function (query) {
        var that = this;
        const scene = decodeURIComponent(query.scene) ? decodeURIComponent(query.scene) : (decodeURIComponent(query.userId) ? decodeURIComponent(query.userId):  null);
        console.log(scene);
        //登录
        that.login(scene);
    },

    onShow: function () {
        if (wx.getStorageSync('token') == '') {
            this.login(null);
        } else {
            //获取userInfo
            $api.userInfo().then(res => {
                if (res.code == 1) {
                    wx.setStorageSync('userInfo', res.data);
                    wx.setStorageSync('user_phone', res.data.mobile);
                    wx.setStorageSync('vip_time_status', res.data.vip_time_status);
                    wx.setStorageSync('vip_time', res.data.vip_time);
                    if (res.data.id_img) {
                        wx.setStorageSync('isRegistered', true)
                    } else {
                        wx.setStorageSync('isRegistered', false)
                    }
                    this.setData({
                        isRegistered: wx.getStorageSync('isRegistered'),
                        vip_time_status: res.data.vip_time_status,
                        vip_time: res.data.vip_time,
                    })
                }
            })
        }
        //判断用户是否注册、会员
        this.setData({
            isRegistered: wx.getStorageSync('isRegistered'),
            vipTimeStatus: wx.getStorageSync('vip_time_status'),
        })
        this.setTags();
        this.getUserCity();
        this.getGoodsList();
    },

    goPublish: function(e)
    {
        wx.navigateTo({
            url: './publish',
        })
    },
    
  //打开位置选择器
  openCityPopup: function (e) {
      console.log(1)
    this.setData({
      cityColumns: area_standard.default,
      showCityPopup: true
    })
  },
  onCloseCityPopup: function (e) {
    this.setData({
      showCityPopup: false
    })
  },

  onChangeCityPopup: function (e) {
    let list = e.detail.values;
    //拼接后端接受的区域格式
    let region = list[0].name + "/" + list[1].name + "/" + list[2].name;
    this.setData({
      region: region,
      showCityPopup: false
    })
  },

    //登录
    login: function (scence) {
        var that = this;
        wx.login({
            success: res => {
                wx.setStorageSync('code', res.code);
                // 传给后台，再经过解析获取用户的 openid获取token
                let param = {
                    code: res.code,
                    Invitees: scence
                }
                console.log(param);
                $api.getLogin(param).then(res => {
                    if (res.code == 1) {
                        wx.setStorageSync('token', res.data.token);
                        wx.setStorageSync('openid', res.data.openid);
                        wx.showLoading({
                            title: '加载中',
                        })
                        //获取userInfo
                        $api.userInfo(param).then(res => {
                            if (res.code == 1) {
                                wx.setStorageSync('userInfo', res.data);
                                wx.setStorageSync('user_phone', res.data.mobile);
                                wx.setStorageSync('vip_time_status', res.data.vip_time_status);
                                wx.setStorageSync('vip_time', res.data.vip_time);
                                if (res.data.id_img) {
                                    wx.setStorageSync('isRegistered', true)
                                } else {
                                    wx.setStorageSync('isRegistered', false)
                                }
                                this.setData({
                                    isRegistered: wx.getStorageSync('isRegistered'),
                                    vip_time_status: res.data.vip_time_status,
                                    vip_time: res.data.vip_time,
                                })
                            }
                        })
                        wx.hideLoading()
                        //加载首页数据
                        //  that.getGoodsList();


                        //查看是否授权
                        wx.getSetting({
                            success: function (res) {
                                // 授权用户信息
                                if (res.authSetting['scope.userInfo']) {
                                    wx.getUserInfo({
                                        lang: 'zh_CN',
                                        success: function (res) {
                                            if (!wx.getStorageSync('city')) {
                                                that.setData({
                                                    city: res.userInfo.city,
                                                    carCity: res.userInfo.city
                                                })
                                                wx.setStorageSync("city", res.userInfo.city);
                                            }
                                        }
                                    })
                                }
                            }
                        });
                    }
                })
            }
        });
    },

    //获取用户信息，判断用户是否已经注册
    //获取用户地理信息
    getUserCity: function () {
        if (wx.getStorageSync("city") == "") {
            let userInfo = wx.getStorageSync('userInfo')
            this.setData({
                city: userInfo.city,
                carCity: userInfo.city
            });
        } else {
            this.setData({
                city: wx.getStorageSync("city"),
                carCity: wx.getStorageSync("city")
            })
        }
    },

    setTags: function () {
        var params = [{
                "key": "name",
                "value": this.data.name,
                'index': ''
            },
            // {
            //     "key": "city",
            //     "value": this.data.carCity,
            //     'index': ''
            // },
            {
                "key": "brand_id",
                "value": this.data.brandName,
                'index': 'brandName'
            },
            {
                "key": "vehicleType",
                "value": this.data.vehicleType2,
                'index': 'vehicleType2'
            },
            {
                "key": "price",
                "value": this.data.priceValue,
                'index': 'priceValue'
            },
            // {"key":"priceValue","value": this.data.priceValue},
            {
                "key": "carAge",
                "value": this.data.carAge2,
                'index': 'carAge2'
            },
            {
                "key": "carDisplacement",
                "value": this.data.carDisplacement,
                'index': 'carDisplacement'
            },
            {
                "key": "mileage",
                "value": this.data.showMileage2,
                'index': 'showMileage2'
            },
            {
                "key": "country",
                "value": this.data.country2,
                'index': 'country2'
            },
            {
                "key": "gearbox",
                "value": this.data.gearbox2,
                'index': 'gearbox2'
            },
            {
                "key": "color",
                "value": this.data.color2,
                'index': 'color2'
            }
        ];
        this.setData({
            'tags': params
        });
    },

    //获取商品列表
    getGoodsList: function () {
        console.log(this.data)
        let pageIndex = this.data.nowpage
        let param = {
            nowpage: this.data.nowpage,
            city: this.data.city == '全国' ? '' : this.data.city,
            brand: this.data.brand,
        }
        $api.newCarSearch(param).then(res => {
            if (res.code == 1) {
                if (pageIndex > 1) {
                    var listBefore = this.data.carSource;
                    var currentList = res.data.list;
                    this.setData({
                        carSource: listBefore.concat(currentList),
                        isHideLoadMore:  (this.data.nowpage + 1) > res.data.sum_page ? true : false,
                        noMore: (this.data.nowpage + 1) > res.data.sum_page ? false : true
                    })
                } else {
                    this.setData({
                        carSource: res.data.list,
                        isHideLoadMore: (this.data.nowpage + 1) > res.data.sum_page ? true : false,
                        noMore: (this.data.nowpage + 1) > res.data.sum_page ? false : true
                    })
                }
            }
        })
    },

    openVehicleDetails: function (event) {
        let userInfo = wx.getStorageSync('userInfo')
        let id = event.currentTarget.dataset.id;
        if (this.data.isRegistered || userInfo.visit_time<5) {
            wx.navigateTo({
                url: '/pages/new/newCarDetail?id=' + id,
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '注册会员查看更多信息',
                success: (res => {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/my/registered'
                        })
                    }
                })
            })
        }
    },

    //下拉加载
    onReachBottom: function () {
        var that = this;
        if (this.data.noMore) {
            this.setData({
                isHideLoadMore: false,
                nowpage: this.data.nowpage + 1,
                noMore: true
            })
            setTimeout(function () {
                that.getGoodsList();
            }, 1000);
        }
    },

    //获取求购城市参数
    getBuyingParam() {
        if (wx.getStorageSync('carCity') != '') {
            this.setData({
                carCity: wx.getStorageSync('carCity')
            })
        }
    },

    //获取求购搜索栏参数
    getSearchTag() {
        let searchArray = wx.getStorageSync('searchArray');
        if (searchArray != '') {
            this.setData({
                searchTag: searchArray.searchTag,
                name: searchArray.name,
                tagIsHide: searchArray.tagIsHide,
                tagShow: searchArray.tagShow
            })
        }
        wx.removeStorageSync('searchArray');
    },


    // //重置
    // restAll: function () {

    // }
})